package com.lolc.ihm.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;

import com.lolc.LoLAutoCounterManager;
import com.lolc.bean.Champion;
import com.lolc.ihm.Constants;
import com.lolc.ihm.MainWindow;
import com.lolc.ihm.component.ComboBoxItem;
import com.lolc.ihm.component.EnnemyPlayerBox;
import com.lolc.ihm.component.MyTeamPlayerBox;
import com.lolc.utils.Constant;

public class SaveChampionListener implements ActionListener {

	private String groupName;
	private int id;

	public SaveChampionListener(String groupName, int id)
	{		
		this.groupName=groupName;
		this.id=id;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getActionCommand()!=null && "comboBoxChanged".equals(e.getActionCommand()))
		{			
			@SuppressWarnings("unchecked")
			JComboBox<ComboBoxItem> comboBox = (JComboBox<ComboBoxItem>) e.getSource();
			// A champion is selected
			Champion previousSelected = null;
			Champion selected=null;
			if(comboBox.getSelectedIndex() >= 0)
			{	
				String selectedChampionId=((ComboBoxItem)comboBox.getSelectedItem()).getId();				
				if(this.groupName!=null && LoLAutoCounterManager.getInstance().getChampionsMap()!=null && LoLAutoCounterManager.getInstance().getChampionsMap().get(selectedChampionId)!=null)
				{
					selected= LoLAutoCounterManager.getInstance().getChampionsMap().get(selectedChampionId);
					if(this.groupName.startsWith(Constants.GROUP_MY_TEAM_CHAMPIONS))
					{
						if(LoLAutoCounterManager.getInstance().getMyTeamSelections()[this.id]!=null)
							previousSelected = LoLAutoCounterManager.getInstance().getMyTeamSelections()[this.id].getChampion();
						
						LoLAutoCounterManager.getInstance().setMyTeamChampionAtPosition(id, selected);
					}
					else if(this.groupName.startsWith(Constants.GROUP_ENNEMY_TEAM_CHAMPIONS))
					{	
						if(LoLAutoCounterManager.getInstance().getEnnemySelections()[this.id]!=null)
							previousSelected = LoLAutoCounterManager.getInstance().getEnnemySelections()[this.id].getChampion();
						LoLAutoCounterManager.getInstance().setEnnemyChampionAtPosition(id, selected);
					}
					else if(this.groupName.startsWith(Constants.GROUP_TEAM_BANNED_CHAMPIONS))
					{
						previousSelected = LoLAutoCounterManager.getInstance().getBannedChampions()[this.id];
						LoLAutoCounterManager.getInstance().setBannedChampionAtPosition(this.id,selected);
					}
					else if(this.groupName.startsWith(Constants.GROUP_ENNEMY_BANNED_CHAMPIONS))
					{
						previousSelected = LoLAutoCounterManager.getInstance().getBannedChampions()[Constant.NUMBER_BANNED_CHAMPIONS_PER_TEAM+this.id];
						LoLAutoCounterManager.getInstance().setBannedChampionAtPosition(Constant.NUMBER_BANNED_CHAMPIONS_PER_TEAM+this.id,selected);
					}
				}				
			}
			//Champion is removed
			else
			{
				if(this.groupName.startsWith(Constants.GROUP_MY_TEAM_CHAMPIONS))
				{		
					if(LoLAutoCounterManager.getInstance().getMyTeamSelections()[this.id]!=null)
						previousSelected = LoLAutoCounterManager.getInstance().getMyTeamSelections()[this.id].getChampion();
					LoLAutoCounterManager.getInstance().setMyTeamChampionAtPosition(id, null);
				}
				else if(this.groupName.startsWith(Constants.GROUP_ENNEMY_TEAM_CHAMPIONS))
				{				
					if(LoLAutoCounterManager.getInstance().getEnnemySelections()[this.id]!=null)
						previousSelected = LoLAutoCounterManager.getInstance().getEnnemySelections()[this.id].getChampion();
					LoLAutoCounterManager.getInstance().setEnnemyChampionAtPosition(id, null);
				}
				else if(this.groupName.startsWith(Constants.GROUP_TEAM_BANNED_CHAMPIONS))
				{
					previousSelected = LoLAutoCounterManager.getInstance().getBannedChampions()[this.id];
					LoLAutoCounterManager.getInstance().setBannedChampionAtPosition(this.id,null);
				}
				else if(this.groupName.startsWith(Constants.GROUP_ENNEMY_BANNED_CHAMPIONS))
				{
					previousSelected = LoLAutoCounterManager.getInstance().getBannedChampions()[Constant.NUMBER_BANNED_CHAMPIONS_PER_TEAM+this.id];
					LoLAutoCounterManager.getInstance().setBannedChampionAtPosition(Constant.NUMBER_BANNED_CHAMPIONS_PER_TEAM+this.id,null);
				}
			}
			
			if(selected!=null)
			{
				filterList("REMOVE",selected);
			}
			
			if(previousSelected!=null)
			{
				filterList("ADD",previousSelected);
			}
			
			LoLAutoCounterManager.getLogger().debug(LoLAutoCounterManager.getInstance().toString());
		}
	}

	/**
	 * Remove selected champions from all other lists
	 * or, add unselected champions on all lists.
	 * @param action
	 * @param champion
	 */
	private void filterList(String action, Champion champion)
	{
		//My Team list
		if(MainWindow.getInstance().getMyTeamBox() != null && MainWindow.getInstance().getMyTeamBox().getMyTeamPlayerBoxes() !=null)
		{
			for(int i =0;i<Constant.NUMBER_PLAYER_PER_TEAM;i++)
			{
				if(!(this.id == i && this.groupName.startsWith(Constants.GROUP_MY_TEAM_CHAMPIONS)))
				{
					MyTeamPlayerBox playerBox  = MainWindow.getInstance().getMyTeamBox().getMyTeamPlayerBoxes().get(i);
					if(playerBox !=null && playerBox.getChampionCB()!=null)
					{
						updateComboBoxList(playerBox.getChampionCB(),action, champion);
					}
				}
			}
		}

		//Ennemy team list
		if(MainWindow.getInstance().getEnnemyBox() != null && MainWindow.getInstance().getEnnemyBox().getEnmemylayerBoxes() !=null)
		{
			for(int i =0;i<Constant.NUMBER_PLAYER_PER_TEAM;i++)
			{
				if(!(this.id == i && this.groupName.startsWith(Constants.GROUP_ENNEMY_TEAM_CHAMPIONS)))
				{
					EnnemyPlayerBox ennemyPlayerBox  =  MainWindow.getInstance().getEnnemyBox().getEnmemylayerBoxes().get(i);
					if(ennemyPlayerBox !=null  && ennemyPlayerBox.getChampionCB()!=null)
					{
						updateComboBoxList(ennemyPlayerBox.getChampionCB(),action, champion);
					}
				}
			}				
		}

		//My banned champions 
		if(MainWindow.getInstance().getMyTeamBox().getBannedChampionBox() !=null && MainWindow.getInstance().getMyTeamBox().getBannedChampionBox().getChampionsCBlist() !=null)
		{
			for(int i =0;i<Constant.NUMBER_BANNED_CHAMPIONS_PER_TEAM;i++)
			{
				if(!(this.id == i && this.groupName.startsWith(Constants.GROUP_TEAM_BANNED_CHAMPIONS)))
				{
					JComboBox<ComboBoxItem> comboBox  =   MainWindow.getInstance().getMyTeamBox().getBannedChampionBox().getChampionsCBlist().get(i);
					if(comboBox !=null )
					{
						updateComboBoxList(comboBox,action, champion);
					}
				}
			}		
		}

		//Ennemy banned champions 
		if(MainWindow.getInstance().getEnnemyBox().getBannedChampionBox() !=null && MainWindow.getInstance().getEnnemyBox().getBannedChampionBox().getChampionsCBlist() !=null)
		{
			for(int i =0;i<Constant.NUMBER_BANNED_CHAMPIONS_PER_TEAM;i++)
			{
				if(!(this.id == i && this.groupName.startsWith(Constants.GROUP_ENNEMY_BANNED_CHAMPIONS)))
				{
					JComboBox<ComboBoxItem> comboBox  =   MainWindow.getInstance().getEnnemyBox().getBannedChampionBox().getChampionsCBlist().get(i);
					if(comboBox !=null )
					{
						updateComboBoxList(comboBox,action, champion);
					}
				}
			}		
		}
	}
	
	/**
	 * Add or remove item in comboBox
	 * @param comboBox
	 * @param action
	 * @param champion
	 */
	private void updateComboBoxList(JComboBox<ComboBoxItem> comboBox, String action, Champion champion)
	{		

		if(champion !=null && champion.getId()!=null)
		{
			//Disable actions listeners to avoid firing event on adding on removing element
			ActionListener[] actions = comboBox.getActionListeners();
			for(int tmp=0; tmp<actions.length;tmp++)
			{
				comboBox.removeActionListener(actions[tmp]);
			}
			
			//Update list
			if("REMOVE".equals(action))
			{
				comboBox.removeItem(new ComboBoxItem(champion.getId(), champion.getName()));
			}
			else if("ADD".equals(action))
			{
				comboBox.insertItemAt(new ComboBoxItem(champion.getId(), champion.getName()),getIndexPositionForInsert(comboBox,champion));
			}

			//Enable action listeners
			for(int tmp=0; tmp<actions.length;tmp++)
			{
				comboBox.addActionListener(actions[tmp]);
			}
		}
		
	}
	
	/**
	 * Get the position to insert the champion as the list is sorted alphabetically
	 * @param comboBox
	 * @param champion
	 * @return
	 */
	public int getIndexPositionForInsert(JComboBox<ComboBoxItem> comboBox, Champion champion)
	{
		int size=comboBox.getItemCount();

		int index=0;
		//  Determine where to insert element to keep model in sorted order            
		for (index = 0; index < size; index++) {
			ComboBoxItem c = (ComboBoxItem) comboBox.getItemAt(index);
			if (c.compareTo(new ComboBoxItem(champion.getId(), champion.getName())) > 0) {
				break;
			}
		}
		return index;
	}
}
